package pageesdto

import (
	"context"
	"fmt"
	"gitee.com/ichub/webcli/common/base/baseconfig"
	"gitee.com/ichub/webcli/common/base/baseutils"
	"gitee.com/ichub/webcli/common/base/baseutils/jsonutils"
	"gitee.com/ichub/webcli/common/ichublog"
	"gitee.com/ichub/webcli/model"
	"github.com/olivere/elastic"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	"testing"
)

//: Elasticsearch实现查询性能的方法包括：
//
//缓存：Elasticsearch可以使用缓存技术，以提高查询性能。这样，在查询时，Elasticsearch可以从缓存中获取数据，以提高查询性能。
//分页：Elasticsearch可以使用分页技术，以减少查询结果的数量，提高查询速度。这样，在查询时，Elasticsearch可以返回满足条件的文档，以提高查询性能。
//排序：Elasticsearch可以使用排序技术，以确保查询结果的有序性，提高查询准确性。这样，在查询时，Elasticsearch可以返回有序的文档，以提高查询性能。
//聚合：Elasticsearch可以使用聚合技术，以对查询结果进行分组和统计，提高查询的可读性和可用性。这样，在查询时，Elasticsearch可以返回聚合后的文档，以提高查询性能。
//

// 原文链接：https://blog.csdn.net/universsky2015/article/details/135783799
var indexName = "ichub_sys_dept"
var esClient = NewPageEsRequest(indexName)

func init() {
	var clientDto = baseconfig.NewElasticClientDto()
	clientDto.URL = "http://192.168.14.58:9200"
	clientDto.Username = "elastic"
	clientDto.Password = "123456"
	esClient.Ini(clientDto)
	esClient.Open()
}

func Test0001_Query(t *testing.T) {
	esClient.Eq("message", "打酱油的一天")
	esClient.OrderBy("user", "desc")
	esClient.EsQuery()

}

func Test0002_FindById(t *testing.T) {
	esClient.EsFindBy("1")

}

func Test0003_EsQuery(t *testing.T) {
	esClient.IndexName = indexName
	query := elastic.NewRangeQuery("dept_id").Gte(553270041122963456).Lte(553270041122963456)

	var ctx = context.Background()
	res, err := esClient.EsClient.Client().Search().Index(esClient.IndexName).Query(query).From(0).Size(2).Pretty(true).Do(ctx)
	//	res, err := esClient.EsClient.Client().Search().Index(esClient.IndexName).From(0).Size(3).Pretty(true).Execute(ctx)
	//	esClient.EsQuery()

	if err != nil {
		logrus.Error(err)
	}
	logrus.Info(jsonutils.ToJsonPretty(res))
}

func Test0004_EsQuery(t *testing.T) {
	esClient.IndexName = "weibo"
	esClient.OrderBy("tags", "asc")
	r, _ := esClient.EsQuery()
	assert.Equal(t, 0, r.Status)

}

const mapping = `
{
  "mappings": {
    "properties": {
      "user": {
        "type": "keyword"
      },
      "message": {
        "type": "text"
      },
      "image": {
        "type": "keyword"
      },
      "created": {
        "type": "date"
      },
      "tags": {
        "type": "keyword"
      },
      "location": {
        "type": "geo_point"
      },
      "suggest_field": {
        "type": "completion"
      }
    }
  }
}`

func Test0005_CreateIndex(t *testing.T) {
	b, err := esClient.EsCreateIndex("weibo1", mapping)
	logrus.Info(b, err)
}

func Test0006_esSaveRaw(t *testing.T) {

	var id int64 = 1 // basefuncs.RuleFuncs.SnowflakeNextId()
	var sysDept = &model.Department{}

	// 使用client创建一个新的文档
	indexRep, err := esClient.client().Index().
		Index(indexName).          // 设置索引名称
		Id(baseutils.Any2Str(id)). // 设置文档id
		BodyJson(sysDept).         // 指定前面声明的微博内容
		Do(context.Background())   // 执行请求，需要传入一个上下文对象
	if err != nil {
		logrus.Error(err)
	}
	logrus.Printf("文档Id %s, 索引名 %s\n", indexRep.Id, indexRep.Index)

}
func Test0006_esSaveIndex(t *testing.T) {
	esClient.IndexName = indexName

	var id int64 = 1 // basefuncs.RuleFuncs.SnowflakeNextId()
	model := model.Department{}
	r, err := esClient.esSaveIndex(esClient.Id2Str(id), model)
	if err != nil {
		logrus.Error(err)
	}
	ichublog.IchubLog.Println(r)
}

func Test0007_EsQuerysDept(t *testing.T) {
	esClient.IndexName = indexName
	esClient.PageSize = 2
	//esClient.Eq("dept_id", "553251751520632832")
	//esClient.OrderBy("dept_id", "desc")
	//	"email": "leijmdas@163.com",
	//	esClient.Like("email", "s@236")
	//esClient.Like("email", "s@236.com")
	esClient.In("dept_id", []interface{}{"553270041122963456"})
	esClient.Between("dept_id", []interface{}{"553270041122963456", "553270041122963456"})
	esClient.EsQuery()

}
func Test0008_EsQuerysDeptResult(t *testing.T) {
	esClient.IndexName = indexName
	esClient.PageSize = 1
	//esClient.Eq("dept_id", "553251751520632832")
	esClient.OrderBy("create_time", "asc")
	esClient.OrderBy("order_nm", "desc")
	//	"email": "leijmdas@163.com",
	//esClient.Like("email", "s@236")
	//	esClient.Like("email", "leijmdas@163.com")
	//	esClient.Between("dept_id", []any{"553263647174950912", "553263647174950912"})
	result, err := esClient.EsQueryResult(false)
	logrus.Error(err)
	logrus.Info(result.ToPrettyString())
	ichublog.Log(result.ToPrettyString())
	assert.Equal(t, 200, result.Code)
}

//https://blog.csdn.net/K346K346/article/details/120906440

func Test0008_EsCount(t *testing.T) {
	esClient.IndexName = indexName
	esClient.PageSize = 2
	//esClient.Eq("dept_id", "553251751520632832")
	esClient.OrderBy("create_time", "asc")
	//	"email": "leijmdas@163.com",
	//	esClient.Like("email", "s@236")
	//esClient.Like("email", "leijmdas@163.com")
	esClient.Between("dept_id", []interface{}{"553263647174950912", "553263647174950912"})
	var c, r = esClient.EsCount()
	fmt.Println(c, r)
}

// path, _, err := client.GetMapping().Index(test.Indices...).Type(test.Types...).buildURL()
func Test0009_EsGetMappiong(t *testing.T) {
	var r, _ = esClient.client().GetMapping().Index(indexName).Type().Do(context.Background())

	logrus.Info(jsonutils.ToJsonPretty(r))

}
func Test0010_EsGetMappiong(t *testing.T) {
	var getMapping, _ = esClient.EsGetMapping(indexName) //Type().Execute(context.Background())
	getMapping, _ = esClient.EsGetMapping("weibo1")      //Type().Execute(context.Background())

	logrus.Info(jsonutils.ToJsonPretty(getMapping))

}

func Test0012_EsQuery(t *testing.T) {
	esClient.IndexName = "ichub_sys_dept"
	esClient.PageSize = 2
	esClient.PageCurrent = 1
	//	esClient.OrderBy("tags", "asc")
	result, _ := esClient.EsQueryResult(false)
	assert.Equal(t, 200, result.Code)

}
